﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.Services;
using DWF.Studio.Share.Log;
using DWF.Studio.Views;
using System;
using System.Activities;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Windows;
using WpfMessageBoxLibrary;

namespace DWF.Studio
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private IEngineIPCService _scriptEngineIPCService = null;
        private IConfigService _configService = null;
        private IAppService _appService = null;

        public App()
        {
            _scriptEngineIPCService = EngineIPCService.Instance;
            _configService = new ConfigService();
            _appService = AppService.Instance;

            //主线程异常处理
            this.DispatcherUnhandledException += (sender, e) =>
            {
                WindowLoading.CloseWindow();

                string msg = e.Exception.Message;
                if (e.Exception is CustomException)
                {
                    msg = e.Exception.Message;
                    LogHelper.Error(e.Exception.InnerException);
                }
                else if (e.Exception is NotImplementedException)
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_NotImplementedException");
                    LogHelper.Error(e.Exception);
                }
                else if (e.Exception is HttpRequestException || e.Exception.InnerException is HttpRequestException || msg == "发送请求时出错。" || msg.Contains("404"))
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_HttpRequestException");
                    LogHelper.Error(e.Exception);
                }
                else if (e.Exception is System.Threading.Tasks.TaskCanceledException)
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_HttpRequestException");
                    LogHelper.Error(e.Exception);
                }
                else if (e.Exception is SocketException || e.Exception.InnerException is SocketException)
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_SocketException");
                    LogHelper.Error(e.Exception);
                }
                else if (e.Exception is InvalidWorkflowException || e.Exception.InnerException is InvalidWorkflowException)
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_InvalidWorkflowException");
                    LogHelper.Error(e.Exception);
                }
                else if (e.Exception is Win32Exception)  //操作系统使用错误
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_Win32Exception");
                    LogHelper.Error(e.Exception);
                }
                else if (e.Exception is FileNotFoundException)
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_FileNotFound");
                    LogHelper.Error(e.Exception);
                }
                else if (e.Exception is IOException)
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_IOException");
                    LogHelper.Error(e.Exception);
                }
                else
                {
                    msg = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_Exception");
                    LogHelper.Error(e.Exception);
                }

                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                    Image = MessageBoxImage.Error,
                    Text = msg,
                    Title = LocalizationProvider.GetLocalizedString("App_MsgBox_Caption_Exception"),
                };
                Window mainwin = Application.Current.MainWindow;
                MessageBoxResult result = WpfMessageBox.Show(mainwin, ref msgProperties);

                e.Handled = true;
            };

            //其它线程异常处理
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                WindowLoading.CloseWindow();

                LogHelper.Error(e.ExceptionObject);

                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                    Image = MessageBoxImage.Error,
                    Text = LocalizationProvider.GetLocalizedString("App_MsgBox_Msg_Exception"),
                    Title = LocalizationProvider.GetLocalizedString("App_MsgBox_Caption_Exception"),
                };
                Window mainwin = Application.Current.MainWindow;
                MessageBoxResult result = WpfMessageBox.Show(mainwin, ref msgProperties);
            };
        }

        protected override void OnExit(ExitEventArgs e)
        {
            WindowLoading.CloseWindow();

            base.OnExit(e);
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            checkAppInstance();
            setCurrentThreadCulture();
            initIPCSerivce();
        }

        private void setCurrentThreadCulture()
        {
            var sysConfig = _configService.LoadSysConfig();
            _appService.SetLanguage(sysConfig.LangugeId);
        }

        private void initIPCSerivce()
        {
            _scriptEngineIPCService.Start();
        }

        private void checkAppInstance()
        {
            bool isNewInstance = _appService.CheckSingleInstance();
            if (!isNewInstance)
            {
                _appService.Shutdown();
            }
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            _appService.FinalHandle();
        }
    }
}
